/*
* Conditions Of Use
*
* This software was developed by employees of the Sigmatrix(Beijing) Corporation.
* This software is provided by sigmatrix as a service and is expressly
* provided "AS IS."  Sigmatrix MAKES NO WARRANTY OF ANY KIND, EXPRESS, IMPLIED
* OR STATUTORY, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTY OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT
* AND DATA ACCURACY.  Sigmatrix does not warrant or make any representations
* regarding the use of the software or the results thereof, including but
* not limited to the correctness, accuracy, reliability or usefulness of
* the software.
*
* Permission to use this software is contingent upon your acceptance
* of the terms of this agreement.
*
*/
package com.sigmatrix.h5.web.rebate;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.sigmatrix.h5.entity.DisDealerAcct;
import com.sigmatrix.h5.entity.DisDealerAcctRegAudit;
import com.sigmatrix.h5.entity.DisRebateScanCode;
import com.sigmatrix.h5.entity.DisTerminalShop;
import com.sigmatrix.h5.entity.Product;
import com.sigmatrix.h5.enums.PromotionCodeType;
import com.sigmatrix.h5.enums.ShopType;
import com.sigmatrix.h5.enums.UserType;
import com.sigmatrix.h5.service.DisDealerAcctRegAuditService;
import com.sigmatrix.h5.service.DisDealerAcctService;
import com.sigmatrix.h5.service.DisTerminalShopService;
import com.sigmatrix.h5.service.ProductService;
import com.sigmatrix.h5.service.TerminalRebateService;
import com.sigmatrix.h5.utils.CommonUtils;
import com.sigmatrix.h5.utils.SessionUtils;
import com.sigmatrix.h5.web.BaseController;
import com.sigmatrix.h5.web.Result;
import com.sigmatrix.h5.web.args.AcctAuditPageParam;
import com.sigmatrix.h5.web.args.RegistTerminalShopParam;
import com.sigmatrix.h5.web.args.ShopAuditParam;
import com.sigmatrix.h5.web.args.TerminalShopInfoResponse;
import com.sigmatrix.sc.jdbc.common.lang.Page;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 *@ClassName: DistributionAcctRegAuditController
 *@Description: 门店注册审核
 *@author MH
 *@date 2017年8月14日 下午12:23:14
 */
@Api(tags="门店注册")
@RestController
@RequestMapping({"/rebate/regist","/open/rebate/regist"})
public class DistributionAcctRegAuditController extends BaseController{
	
	private Logger logger = Logger.getLogger(DistributionAcctRegAuditController.class);
	
	@Autowired
	private DisTerminalShopService disTerminalShopService;
	
	@Autowired
	private DisDealerAcctRegAuditService disDealerAcctRegAuditService;
	
	@Autowired
	private ProductService productService;
	
	@Autowired
	private TerminalRebateService terminalRebateService;
	
	@Autowired
	private DisDealerAcctService disDealerAcctService;
	
	/**
	 * 分页查询
	 *@Title: findByPage
	 *@Description: 
	 *@return Result
	 *@author MH
	 *@date 2017年8月22日 上午9:42:58
	 *@param vo
	 *@return
	 */
	@ApiOperation("查询门店审核列表")
	@PostMapping("/api/list")
	public Result<Page<DisDealerAcctRegAudit>> findByPage(@RequestBody AcctAuditPageParam vo){
		final DisDealerAcctRegAudit po = new DisDealerAcctRegAudit();
		if(CommonUtils.isNotEmpty(vo)){
			BeanUtils.copyProperties(vo, po);
		}
		DisDealerAcct acct = disDealerAcctService.findById(SessionUtils.getUserId());
		if(UserType.SALES_MAN.value.equals(acct.getUserType())){
			po.setPromotionCode(acct.getPromotionCode());
			po.setPromotionCodeType(PromotionCodeType.SALES_MAN.value);
		}
		po.setDealerId(SessionUtils.getDealerId());
		Page<DisDealerAcctRegAudit> page = disDealerAcctRegAuditService.findAuditList(po, vo.getPageNo(), vo.getPageSize());
		return ok(page);
	}
	
	
//	/**
//	 * 通过openId查询终端店是否存在
//	 *@Title: findByOpenId
//	 *@Description: 
//	 *@return Result
//	 *@author MH
//	 *@date 2017年8月14日 下午10:14:00
//	 *@param openId
//	 *@return
//	 */
//	@ApiOperation(value="通过openId查询",response=DisTerminalShop.class)
//	@GetMapping(value="/api/query",produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
//	public Result<DisTerminalShop> findByOpenId(String openId){
//		logger.info("开始通过openId查询门店 openId="+openId);
//		if(StringUtils.isBlank(openId)){
//			return error("openId不能为空");
//		}
//		//验证该门店是否注册过，如果已经注册过，就把信息返回（根据openId查询）
//		DisTerminalShop shop = disTerminalShopService.getLastApplyInfo(openId);
//		return ok(shop);
//	}
	
	/**
	 * 通过openId查询终端店
	 * @param openId
	 * @return
	 */
	@ApiOperation(value="通过openId查询",response=DisTerminalShop.class)
	@GetMapping(value="/api/query",produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
	public Result<TerminalShopInfoResponse> findByOpenIdV2(String openId){
		logger.info("开始通过openId查询门店 openId="+openId);
		if(StringUtils.isBlank(openId)){
			return error("openId不能为空");
		}
		//验证该门店是否注册过，如果已经注册过，就把信息返回（根据openId查询）
		TerminalShopInfoResponse shop = disTerminalShopService.getLastApplyInfo2(openId);
		return ok(shop);
	}
	
	
	
	
	@ApiOperation("通过主键查询")
	@GetMapping(value="/api/get",produces="application/json")
	public Result<DisDealerAcctRegAudit> findById(Integer id){
		if(CommonUtils.isEmpty(id)) return error("请选择要查询的记录");
		DisDealerAcctRegAudit result = disDealerAcctRegAuditService.findById(id);
		if(CommonUtils.isEmpty(result))return error("没有查询到记录");
		return ok(result);
	}
	/**
	 * 注册终端门店
	 *@Title: registTerminalShop
	 *@Description: 
	 *@return Result
	 *@author MH
	 *@date 2017年8月22日 上午11:06:50
	 *@param vo
	 *@return
	 */
	@ApiOperation(value="注册终端店",response=DisTerminalShop.class)
	@PostMapping(value="/api/regist",produces="application/json")
	public Result<DisTerminalShop> registTerminalShop(@RequestBody RegistTerminalShopParam vo){
		logger.info("开始注册终端门店="+JSONObject.toJSONString(vo));
		//TODO 天喔需求，暂时写死，前端没有时间开发新功能，只能写死在后端，以后一定要抹掉这个入口
		if("-1".equals(vo.getPromotionCode())){
			return ok(disTerminalShopService.directSave(vo));
		}
		//验证必填项
		if(StringUtils.isBlank(vo.getLat()) || StringUtils.isBlank(vo.getLng())){
			return error("经纬度不能为空");
		}
		if(StringUtils.isBlank(vo.getOpenId())){
			return error("openId不能为空");
		}
		if(CommonUtils.isEmpty(vo.getProductId())){
			return error("productId不能为空");
		}
		if(StringUtils.isBlank(vo.getName())){
			return error("name不能为空");
		}
		if(StringUtils.isBlank(vo.getPromotionCode())){
			return error("promotionCode不能为空");
		}
		if(StringUtils.isBlank(vo.getContact())){
			return error("contact不能为空");
		}
		if(StringUtils.isBlank(vo.getMobilePhone())){
			return error("mobilePhone不能为空");
		}
		if(StringUtils.isBlank(vo.getDomain())){
			return error("domain不能为空");
		}
		if(StringUtils.isBlank(vo.getSubDomain())){
			return error("subDomain不能为空");
		}
		if(CommonUtils.isEmpty(vo.getSeqNum())){
			return error("seqNum不能为空");
		}
		//shortMessageService.validateCode(vo.getSmsCode());
		final DisRebateScanCode scanCode = new DisRebateScanCode();
		BeanUtils.copyProperties(vo, scanCode);
		scanCode.setQrCode(vo.getTagCode());
		final DisTerminalShop shop = new DisTerminalShop();
		BeanUtils.copyProperties(vo, shop);
		//新添终端门店类型
		if(CommonUtils.isNotEmpty(vo.getShopType())){
			shop.setType(vo.getShopType().value);
		}else{
			shop.setType(ShopType.GROCERY_STORE.value);
		}
		Product product = productService.findByBasicModuleId(vo.getProductId());
		if(CommonUtils.isEmpty(product)){
			return error("没有查询到产品");
		}
		vo.setProductId(product.getId());
		DisTerminalShop _s = terminalRebateService.scanCode(vo);
		return ok(_s);
	}
	/**
	 * 终端门店审核
	 *@Title: audit
	 *@Description: 
	 *@return Result
	 *@author MH
	 *@date 2017年8月22日 上午11:06:10
	 *@param vo
	 *@return
	 */
	@ApiOperation("终端门店审核")
	@PostMapping("/api/audit")
	public Result<Void> audit(@RequestBody List<ShopAuditParam> vo){
		//final DistributionAcctRegAudit po = new DistributionAcctRegAudit();
		//if(CommonUtils.isNotEmpty(vo)) BeanUtils.copyProperties(vo, po);
		disDealerAcctRegAuditService.audit(vo);
		return ok(null);
	}
}
